package com.example.securitydemo.service;

import com.example.securitydemo.mapper.UserMapper;
import com.example.securitydemo.po.Role;
import com.example.securitydemo.po.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.util.List;

/**
 * @Package: com.example.securitydemo.service
 * @ClassName: UserService
 * @Author: Think
 * @CreateTime: 2021/7/29 13:49
 * @Description:
 */
@Slf4j
@Service
public class UserService implements UserDetailsService {

    @Resource
    private UserMapper userMapper;

    /**
     * 根据用户名去数据库获取用户信息，SpringSecutity会自动进行密码的比对
     * @param username
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 用户名必须是唯一的，不允许重复
        User user = userMapper.getUserByUserName(username);
        if(ObjectUtils.isEmpty(user)){
            throw new UsernameNotFoundException("根据用户名找不到该用户的信息！");
        }
        List<Role> roleList = userMapper.getUserRolesByUserId(user.getUserId());
        user.setRoles(roleList);
        return user;
    }
}
